import socket
import threading

import wx
from faker import Faker


class Client(wx.Frame):
    def __init__(self):
        self.name = Faker('zh_CN').name()
        self.isConnect = False
        self.client_socket = None

        super().__init__(None, title=self.name + '智能聊天室客户端', size=(500, 650))
        self.pl = wx.Panel(self)
        wx.Button(self.pl, label='加入聊天室', pos=(10, 10), size=(220, 40)).Bind(wx.EVT_BUTTON, self.join_chat_room)
        wx.Button(self.pl, label='离开聊天室', pos=(260, 10), size=(220, 40)).Bind(wx.EVT_BUTTON, self.leave_chat_room)
        self.chat_text = wx.TextCtrl(self.pl, pos=(10, 60), size=(470, 400), style=wx.TE_READONLY | wx.TE_MULTILINE)
        self.input_text = wx.TextCtrl(self.pl, pos=(10, 470), size=(470, 80), style=wx.TE_MULTILINE)
        wx.Button(self.pl, label='清空聊天记录', pos=(10, 560), size=(220, 40)).Bind(wx.EVT_BUTTON,
                                                                                     self.clear_chat_record)
        wx.Button(self.pl, label='发送信息', pos=(260, 560), size=(220, 40)).Bind(wx.EVT_BUTTON, self.send_message)

    def join_chat_room(self, event):
        if not self.isConnect:
            try:
                self.client_socket = socket.socket()
                self.client_socket.connect(('127.0.0.1', 8006))
                self.isConnect = True
                # 发送用户名
                self.client_socket.send(self.name.encode('utf8'))
                main_thread = threading.Thread(target=self.recv_data)
                main_thread.daemon = True
                main_thread.start()
            except Exception as e:
                print(f'连接失败: {e}')
                self.isConnect = False
                self.client_socket.close()

    def recv_data(self):
        while self.isConnect:
            data = self.client_socket.recv(1024).decode('utf8')
            self.chat_text.AppendText(data)

    def leave_chat_room(self, event):
        if self.isConnect:
            self.client_socket.send('断开连接'.encode('utf8'))
            self.isConnect = False

    def clear_chat_record(self, event):
        self.chat_text.Clear()

    def send_message(self, event):
        if self.isConnect:
            self.client_socket.send(self.input_text.GetValue().encode('utf8'))
            self.input_text.Clear()


if __name__ == '__main__':
    app = wx.App()
    Client().Show()
    app.MainLoop()
